<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Services\AuthService;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($request, $guards);

        // 用户路由权限检查
        if ($request->is('admin/*') !== false) {
            $authService = new AuthService();
            if (!$authService->canPass($request)) {
                return responseException(__('auth.no_permission'), [], 403);
            }
        }
        return $next($request);
    }

    /**
     * 未授权时操作
     * @param \Illuminate\Http\Request $request
     * @param array $guards
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|void
     * @throws ApiException
     */
    protected function unauthenticated($request, array $guards)
    {
        // 后台操作则返回401 HTTP状态码
        // if ($request->is('admin/api/*')) return responseException(__('auth.failed'), [], 401, 401);
        // if (!$request->is('api/*')) parent::unauthenticated($request, $guards);

        throw new AuthenticationException(__('auth.failed'));
    }
}
